#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdio.h>

#include "util.h"

/*
uint8_t internal_eeprom_read(uint16_t addr) {
  loop_until_bit_is_clear(EECR, EEPE); // wait for last write to finish
  EEAR = addr;
  EECR |= _BV(EERE);        // start EEPROM read
  return EEDR;            // takes only 1 cycle
}

void internal_eeprom_write(uint16_t addr, uint8_t data) {
  loop_until_bit_is_clear(EECR, EEPE); // wait for last write to finish
  EEAR = addr;
  EEDR = data;
  cli();                // turn off interrupts 
  EECR |= _BV(EEMPE);     // these instructions must happen within 4 cycles
  EECR |= _BV(EEPE);
  sei();                // turn on interrupts again
}
*/

 void delay_ms(uint16_t ms) {
  uint16_t delay_count = F_CPU / 17500;
  volatile uint16_t i;

//  return;
  while (ms != 0) {
    for (i=0; i != delay_count; i++);
    ms--;
  }
}

void uart_init(uint16_t brr) {
  UBRR0 = brr;
  UCSR0B = _BV(RXEN0) | _BV(TXEN0);
  UCSR0C = _BV(USBS0) | (3<<UCSZ00);
  DDRD |= _BV(PD1);
  DDRD &= ~_BV(PD0);
}

void uart_putchar(char c) {
  loop_until_bit_is_set(UCSR0A, UDRE0);
  UDR0 = c;
}

char uart_getchar(void) {
  char c;
  loop_until_bit_is_set(UCSR0A, RXC0);
  c = UDR0;
  uart_putchar(c); // echo
  return c;
}

char uart_getch(void) {
  return (UCSR0A & _BV(RXC0));
}

/* TODO: handle backspace */
uint16_t uart_read16(void) {
  uint8_t c;
  uint16_t t=0;
  while ( (c = uart_getchar()) != '\n') {
    if (c == '\r') break;
    if ((c  > '9') || (c < '0'))
      continue;
    //    uart_putchar(c);
    t *= 10;
    t += c-'0';
  }
  //  uart_putchar(c);
  return t;
}

void print_div(void) {
  printf_P(PSTR("---------------------------------\r\n"));
};

